package cn.lxb.netstat.collector;

import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 记录到内存中
 * 
 * @author liuxb
 *
 */
@Slf4j
@RestController
public class CollectController {
	
	@Autowired
	NetstatCollectorProperties properties;
	@Autowired
	AddressRepository addressRepository;	
	
	String confirmCode;
	
	ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();

	@PostConstruct
	public void init() {
		confirmCode = RandomUtil.randomString(6);
		log.info("clear confirmCode:{}", confirmCode);
	}

	@PostMapping("/collect")
	public String collect(@RequestBody @NotNull RecordParam recordParam) {
		log.info("增加地址记录:{}", recordParam);
		addressRepository.save(recordParam);
		return "SUCC";
	}
	
	@PostMapping("/remove")
	public String remove(@RequestBody @NotNull RecordParam recordParam) {
		log.info("删除地址记录:{}", recordParam);
		addressRepository.remove(recordParam);
		return "SUCC";
	}

	@GetMapping("/queryByAppName/{appName}")
	public Set<String> queryByAppName(@PathVariable @NotBlank String serviceName) {
		return addressRepository.queryByAppName(serviceName);
	}

	@GetMapping("/queryAll")
	public Map<String, Set<String>> queryAll() {
		return addressRepository.queryAll();
	}
	
	@GetMapping("/queryByAppNameStr/{serviceName}")
	public String queryByAppNameStr(@PathVariable @NotBlank String serviceName) throws JsonProcessingException {
		String s =  ow.writeValueAsString(queryByAppName(serviceName));
		s="<pre>"+s+"</pre>";
		return s;
	}

	@GetMapping("/queryAllStr")
	public String queryAllStr() throws JsonProcessingException {
		String s = ow.writeValueAsString(queryAll());
		s="<pre>"+s+"</pre>";
		return s;
	}
	
	// 实验性质功能,生产谨慎使用
	@GetMapping("/clear/{confirmCode}")
	public String clear(@PathVariable @NotBlank String confirmCode) {
		if(!confirmCode.equals(this.confirmCode)){
			return "操作确认码错误!";
		}
		addressRepository.clear();
		log.info("已清除地址列表");
		return "SUCC";
	}

}
